<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item v-for="item in breadcrumbs" :key="item.path">
      <span :class="{ 'no-redirect': isLast(item) }" @click="handleLink(item)">
        {{ item.meta?.title }}
      </span>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { useRoute, useRouter, type RouteLocationMatched } from "vue-router";
import type { ComputedRef } from 'vue'

const route = useRoute();
const router = useRouter();

// 获取面包屑数据，过滤掉没有标题的路由
const breadcrumbs: ComputedRef<RouteLocationMatched[]> = computed(() => {
  return route.matched.filter((item) => item.meta?.title);
});

// 判断是否是最后一个面包屑
const isLast = (item: RouteLocationMatched): boolean => {
  const last = breadcrumbs.value[breadcrumbs.value.length - 1];
  return item.path === last.path;
};

// 处理面包屑点击
const handleLink = (item: RouteLocationMatched): void => {
  if (isLast(item)) return;

  // 如果是根路由，直接跳转到首页
  if (item.path === "/") {
    router.push("/");
    return;
  }

  // 如果是父级路由且有子路由，跳转到第一个子路由
  if (item.children && item.children.length > 0) {
    const firstChild = item.children.find((child) => !child.children);
    if (firstChild) {
      router.push(firstChild.path);
      return;
    }
  }

  // 否则跳转到当前路由
  router.push(item.path);
};

defineOptions({
  name: 'Breadcrumb'
})
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  line-height: 60px;

  :deep(.el-breadcrumb__inner) {
    cursor: pointer;
    color: var(--el-text-color-primary);
    font-weight: normal;

    &:hover {
      color: var(--el-color-primary);
    }

    &.no-redirect {
      cursor: text;
      color: var(--el-text-color-secondary);

      &:hover {
        color: var(--el-text-color-secondary);
      }
    }
  }

  :deep(.el-breadcrumb__separator) {
    color: var(--el-text-color-primary);
  }
}

// 深色模式适配
:deep(html.dark) {
  .el-breadcrumb {
    .el-breadcrumb__inner {
      color: var(--el-text-color-primary);

      &:hover {
        color: var(--el-color-primary);
      }

      &.no-redirect {
        color: var(--el-text-color-secondary);

        &:hover {
          color: var(--el-text-color-secondary);
        }
      }
    }

    .el-breadcrumb__separator {
      color: var(--el-text-color-primary);
    }
  }
}
</style>
